package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 * 底层基于代理
 */
//拦截copntroller
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j //输出日志
@Component
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        ex.printStackTrace();
        String message = ex.getMessage();
        String[] split = message.split("'");
        return R.error(split[1] +"已存在");
    }


    /**
     * 异常处理方法
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }
}